#include "SeqList.h"

void SLInit(SL* ps)
{
	assert(ps);
	ps->_a = NULL;
	ps->_sz = ps->_capacity = 0;
}
void SLDestroy(SL* ps)
{
	assert(ps);
	free(ps->_a);
	ps->_a = NULL;
	ps->_sz = ps->_capacity = 0;
}
void SLPrint(SL* ps)
{
	assert(ps);
	for (int i = 0; i < ps->_sz; i++)
		printf("%d ", ps->_a[i]);
	printf("\n");
}
static void SLCheckCapacity(SL* ps)
{
	if (ps->_sz == ps->_capacity)
	{
		int newcapacity = ps->_capacity == 0 ? 4 : 2 * ps->_capacity;
		SDataType* tmp = (SDataType*)realloc(ps->_a, sizeof(SDataType) * newcapacity);
		if (tmp == NULL)
		{
			printf("malloc fail\n");
			exit(1);
		}
		ps->_a = tmp;
		ps->_capacity = newcapacity;
	}
}
void SLPushBack(SL* ps, SDataType data)
{
	assert(ps);
	SLCheckCapacity(ps);
	ps->_a[ps->_sz++] = data;
}
void SLPushFront(SL* ps, SDataType data)
{
	assert(ps);
	SLCheckCapacity(ps);
	int end = ps->_sz;
	while (end > 0)
	{
		ps->_a[end] = ps->_a[end - 1];
		end--;
	}
	ps->_a[0] = data;
	ps->_sz++;
}
void SLPopBack(SL* ps)
{
	assert(ps);
	assert(!SLEmpty(ps));
	ps->_sz--;
}
void SLPopFront(SL* ps)
{
	assert(ps);
	assert(!SLEmpty(ps));
	int i = 0;
	while (i < ps->_sz)
	{
		ps->_a[i] = ps->_a[i + 1];
		i++;
	}
	ps->_sz--;
}
void SLInsert(SL* ps, size_t pos, SDataType data)
{
	assert(ps);
	SLCheckCapacity(ps);
	int end = ps->_sz;
	while (end > pos)
	{
		ps->_a[end] = ps->_a[end - 1];
		end--;
	}
	ps->_a[pos] = data;
	ps->_sz++;
}
void SLErase(SL* ps, size_t pos)
{
	assert(ps);
	assert(!SLEmpty(ps));
	while (pos < ps->_sz)
	{
		ps->_a[pos] = ps->_a[pos + 1];
		pos++;
	}
	ps->_sz--;
}
int SLSize(SL* ps)
{
	assert(ps);
	return ps->_sz;
}
bool SLEmpty(SL* ps)
{
	return SLSize(ps) == 0;
}